from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc, asc, func
import os
import uuid
from database.connection import get_db
from database.models import UserLevel, AwardPoints
from models.levels import (
    UserLevelCreate, UserLevelUpdate, UserLevelResponse, UserLevelListResponse,
    AwardPointsCreate, AwardPointsUpdate, AwardPointsResponse, AwardPointsListResponse,
    LevelQuery, AwardQuery
)
from utils.auth import get_current_user

router = APIRouter(prefix="/levels", tags=["等级积分管理"])


# ==================== 用户等级管理 ====================

@router.get("/user-levels", summary="获取用户等级列表")
async def get_user_levels(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """
    获取用户等级列表
    支持分页和关键词搜索
    """
    try:
        # 构建查询条件
        query = db.query(UserLevel)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                UserLevel.level_name.contains(keyword)
            )
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        levels = query.order_by(UserLevel.required_points.asc()).offset((page - 1) * size).limit(size).all()
        
        return {
            "code": 200,
            "msg": "获取等级列表成功",
            "data": {
                "total": total,
                "items": [UserLevelResponse.model_validate(level) for level in levels]
            }
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取等级列表失败: {str(e)}"
        }


@router.post("/user-levels", summary="创建用户等级")
async def create_user_level(
    level_data: UserLevelCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    创建新的用户等级
    需要管理员权限
    """
    try:
        # 检查等级ID是否已存在
        if level_data.level_id:
            existing_level = db.query(UserLevel).filter(UserLevel.level_id == level_data.level_id).first()
            if existing_level:
                return {
                    "code": 400,
                    "msg": "等级ID已存在"
                }
        
        # 检查等级名称是否已存在
        existing_name = db.query(UserLevel).filter(UserLevel.level_name == level_data.level_name).first()
        if existing_name:
            return {
                "code": 400,
                "msg": "等级名称已存在"
            }
        
        # 创建新等级
        new_level = UserLevel(
            level_id=level_data.level_id,
            level_name=level_data.level_name,
            required_points=level_data.required_points,
            upgrade_points=level_data.upgrade_points,
            url=level_data.url or "",
            url2=level_data.url2 or ""
        )
        
        db.add(new_level)
        db.commit()
        db.refresh(new_level)
        
        return {
            "code": 200,
            "msg": "创建等级成功",
            "data": UserLevelResponse.model_validate(new_level)
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建等级失败: {str(e)}"
        }


@router.get("/user-levels/{level_id}", summary="获取用户等级详情")
async def get_user_level_detail(
    level_id: int,
    db: Session = Depends(get_db)
):
    """
    根据等级ID获取等级详情
    """
    try:
        level = db.query(UserLevel).filter(UserLevel.level_id == level_id).first()
        
        if not level:
            return {
                "code": 404,
                "msg": "等级不存在"
            }
        
        return {
            "code": 200,
            "msg": "获取等级详情成功",
            "data": UserLevelResponse.model_validate(level)
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取等级详情失败: {str(e)}"
        }


@router.put("/user-levels/{level_id}", summary="更新用户等级")
async def update_user_level(
    level_id: int,
    level_data: UserLevelUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    更新用户等级信息
    需要管理员权限
    """
    try:
        level = db.query(UserLevel).filter(UserLevel.level_id == level_id).first()
        
        if not level:
            return {
                "code": 404,
                "msg": "等级不存在"
            }
        
        # 检查等级名称是否与其他等级重复
        if level_data.level_name and level_data.level_name != level.level_name:
            existing_name = db.query(UserLevel).filter(
                and_(UserLevel.level_name == level_data.level_name, UserLevel.level_id != level_id)
            ).first()
            if existing_name:
                return {
                    "code": 400,
                    "msg": "等级名称已存在"
                }
        
        # 更新字段
        update_data = level_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(level, field, value)
        
        db.commit()
        db.refresh(level)
        
        return {
            "code": 200,
            "msg": "更新等级成功",
            "data": UserLevelResponse.model_validate(level)
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新等级失败: {str(e)}"
        }


@router.delete("/user-levels/{level_id}", summary="删除用户等级")
async def delete_user_level(
    level_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除用户等级
    需要管理员权限
    """
    try:
        level = db.query(UserLevel).filter(UserLevel.level_id == level_id).first()
        
        if not level:
            return {
                "code": 404,
                "msg": "等级不存在"
            }
        
        db.delete(level)
        db.commit()
        
        return {
            "code": 200,
            "msg": "删除等级成功"
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除等级失败: {str(e)}"
        }


# ==================== 奖项积分管理 ====================

@router.get("/award-points", summary="获取奖项积分列表")
async def get_award_points(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """
    获取奖项积分列表
    支持分页和关键词搜索
    """
    try:
        # 构建查询条件
        query = db.query(AwardPoints)
        
        # 关键词搜索
        if keyword:
            query = query.filter(
                AwardPoints.award_name.contains(keyword)
            )
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        awards = query.order_by(AwardPoints.points.desc()).offset((page - 1) * size).limit(size).all()
        
        return {
            "code": 200,
            "msg": "获取奖项列表成功",
            "data": {
                "total": total,
                "items": [AwardPointsResponse.model_validate(award) for award in awards]
            }
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取奖项列表失败: {str(e)}"
        }


@router.post("/award-points", summary="创建奖项积分")
async def create_award_points(
    award_data: AwardPointsCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    创建新的奖项积分
    需要管理员权限
    """
    try:
        # 检查奖项名称是否已存在
        existing_award = db.query(AwardPoints).filter(AwardPoints.award_name == award_data.award_name).first()
        if existing_award:
            return {
                "code": 400,
                "msg": "奖项名称已存在"
            }
        
        # 创建新奖项
        new_award = AwardPoints(
            award_name=award_data.award_name,
            points=award_data.points
        )
        
        db.add(new_award)
        db.commit()
        db.refresh(new_award)
        
        return {
            "code": 200,
            "msg": "创建奖项成功",
            "data": AwardPointsResponse.model_validate(new_award)
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建奖项失败: {str(e)}"
        }


@router.get("/award-points/{award_id}", summary="获取奖项积分详情")
async def get_award_points_detail(
    award_id: int,
    db: Session = Depends(get_db)
):
    """
    根据奖项ID获取奖项详情
    """
    try:
        award = db.query(AwardPoints).filter(AwardPoints.id == award_id).first()
        
        if not award:
            return {
                "code": 404,
                "msg": "奖项不存在"
            }
        
        return {
            "code": 200,
            "msg": "获取奖项详情成功",
            "data": AwardPointsResponse.model_validate(award)
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取奖项详情失败: {str(e)}"
        }


@router.put("/award-points/{award_id}", summary="更新奖项积分")
async def update_award_points(
    award_id: int,
    award_data: AwardPointsUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    更新奖项积分信息
    需要管理员权限
    """
    try:
        award = db.query(AwardPoints).filter(AwardPoints.id == award_id).first()
        
        if not award:
            return {
                "code": 404,
                "msg": "奖项不存在"
            }
        
        # 检查奖项名称是否与其他奖项重复
        if award_data.award_name and award_data.award_name != award.award_name:
            existing_name = db.query(AwardPoints).filter(
                and_(AwardPoints.award_name == award_data.award_name, AwardPoints.id != award_id)
            ).first()
            if existing_name:
                return {
                    "code": 400,
                    "msg": "奖项名称已存在"
                }
        
        # 更新字段
        update_data = award_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(award, field, value)
        
        db.commit()
        db.refresh(award)
        
        return {
            "code": 200,
            "msg": "更新奖项成功",
            "data": AwardPointsResponse.model_validate(award)
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新奖项失败: {str(e)}"
        }


@router.delete("/award-points/{award_id}", summary="删除奖项积分")
async def delete_award_points(
    award_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    """
    删除奖项积分
    需要管理员权限
    """
    try:
        award = db.query(AwardPoints).filter(AwardPoints.id == award_id).first()
        
        if not award:
            return {
                "code": 404,
                "msg": "奖项不存在"
            }
        
        db.delete(award)
        db.commit()
        
        return {
            "code": 200,
            "msg": "删除奖项成功"
        }
    
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除奖项失败: {str(e)}"
        }


